<template>
  <div>
    <!--导航栏-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--警告栏-->
      <el-alert
        title="只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!--选择分类下拉框-->
      <span>选择商品分类&nbsp;:&nbsp;</span>
      <el-cascader
        v-model="selectKeys"
        :options="cateList"
        :props="cascaderProps"
        clearable
        @change="handleChange"
      >
      </el-cascader>

    <!--选项卡-->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!--动态属性标签页-->
        <el-tab-pane label="动态属性" name="many">
          <el-button size='mini' type="primary" :disabled="isDisabled" @click="addParamDialogVisible=true">添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="mini" class="el-icon-edit" type="primary" @click="showEditParamDialog(scope.row)" >编辑</el-button>
                <el-button size="mini" class="el-icon-delete" type="danger" @click="deleteParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!--静态属性标签页-->
        <el-tab-pane label="静态属性" name="only">
          <el-button size="mini" type="primary" :disabled="isDisabled" @click="addParamDialogVisible=true">添加属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index,scope.row)"
                >
                  {{item}}
                </el-tag>
                <!--el-inout上未封装keyup事件,组件上使用native修饰符可用原生js事件名-->
                <el-input
                  size="small"
                  v-if="scope.row.inputVisible"
                  class="input-tag" ref="saveTagInput"
                  v-model="scope.row.inputValue"
                  @blur="saveInput(scope.row)"
                  @keyup.enter.native="saveInput(scope.row)"
                >
                </el-input>
                <el-button size="mini" v-else @click="getInput(scope.row)">+New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="mini" class="el-icon-edit" type="primary" @click="showEditParamDialog(scope.row)">编辑</el-button>
                <el-button size="mini" class="el-icon-delete" type="danger" @click="deleteParamDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数对话框-->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamDialogVisible"
      width="50%"
      @close="addParamDialogClosed"
    >
      <el-form label-width="80px" :model="addParamForm" :rules="addParamFormRules" ref="addParamFormRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addParamDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
      </template>
    </el-dialog>

    <!--编辑参数对话框-->
    <el-dialog
      :title="'编辑'+titleText"
      :visible.sync="editParamDialogVisible"
      width="50%"
      @close="editParamDialogClosed"
    >
      <el-form label-width="80px" :model="editParamForm" :rules="editParamFormRules" ref="editParamFormRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editParamDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      selectKeys: [],
      cateList: [],
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: false
      },
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      // 添加对话框数据
      addParamDialogVisible: false,
      addParamFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
      },
      addParamForm: { attr_name: '' },
      // 编辑对话框数据
      editParamDialogVisible: false,
      // 临时变量保存表单数据,避免编辑时页面同步更新
      paramObj: {},
      editParamFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
      },
      editParamForm: { attr_name: '' }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    handleChange () {
      if (this.selectKeys.length !== 3) {
        this.$message.error('请务必选择三级分类')
        this.selectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      this.getParamsData()
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.$message.success('获取商品分类列表成功')
      this.cateList = res.data
    },
    handleClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        return false
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      this.$message.success('获取参数列表成功')
      // attr_val转换为数组,做成标签在下拉表展示
      res.data.forEach(val => {
        val.attr_vals = val.attr_vals ? val.attr_vals.split(',') : []
        val.inputVisible = false
        val.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },
    addParamDialogClosed () {
      this.$refs.addParamFormRef.resetFields()
    },
    addParam () {
      this.$refs.addParamFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: 'a,b,c,d'
        })
        if (res.meta.status !== 201) return this.$message.error(`添加${this.titleText}失败`)
        this.$message.success(`添加${this.titleText}成功`)
        this.getParamsData()
        this.addParamDialogVisible = false
      })
    },
    showEditParamDialog (scope) {
      this.paramObj = scope
      this.editParamDialogVisible = true
      this.editParamForm.attr_name = this.paramObj.attr_name
    },
    editParamDialogClosed () {
      this.$refs.editParamFormRef.resetFields()
    },
    async editParam () {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.paramObj.attr_id}`, {
        attr_name: this.editParamForm.attr_name,
        attr_sel: this.activeName,
        attr_vals: 'a,b,c,d'
      })
      if (res.meta.status !== 200) return this.$message.error(`编辑${this.titleText}失败`)
      this.$message.success(`编辑${this.titleText}成功`)
      this.getParamsData()
      this.editParamDialogVisible = false
    },
    async deleteParam (id) {
      const result = await this.$confirm(`此操作将永久删除该${this.titleText}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error(`删除${this.titleText}失败`)
      this.$message.success(`删除${this.titleText}成功`)
      this.getParamsData()
    },
    // 点击+tag显示输入框
    getInput (val) {
      val.inputVisible = true
      // 延迟获得焦点操作,不能和页面刷新同步进行
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 保存输入输入框内容到标签
    async saveInput (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.saveTagValue(row)
    },
    // 提交新增标签到server
    async saveTagValue (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('提交标签失败')
      this.$message.success('提交标签成功')
    },
    // 删除标签
    deleteTag (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveTagValue()
    }
  },
  computed: {
    isDisabled () {
      // 选择不是三级分类,就返回true,disable生效
      return this.selectKeys.length !== 3
    },
    cateId () {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[this.selectKeys.length - 1]
      }
      return null
    },
    titleText () {
      return this.activeName === 'many' ? '动态参数' : '静态参数'
    }
  }
}
</script>

<style scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-tag{
  margin: 10px;
}
  .input-tag{
    width: 120px;
  }
</style>
